package com.guoguo.api;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.DoubleArraySerializer;
import com.guoguo.base.BaseController;
import com.guoguo.base.StaticResource;
import com.guoguo.entity.*;
import com.guoguo.entity.vo.UsersVO;
import com.guoguo.enums.PayEnum;
import com.guoguo.service.AlbumService;
import com.guoguo.service.BuysService;
import com.guoguo.service.IPayService;
import com.guoguo.service.IUserExtService;
import com.guoguo.utils.AliOssUtils;
import com.guoguo.utils.RedisUtils;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by Administrator on 2017/9/12 0012.
 */

     /*
                           _ooOoo_
                          o8888888o
                          88" . "88
                          (| -_- |)
                          O\  =  /O
                       ____/`---'\____
                     .'  \\|     |//  `.
                    /  \\|||  :  |||//  \
                   /  _||||| -:- |||||-  \
                   |   | \\\  -  /// |   |
                   | \_|  ''\---/''  |   |
                   \  .-\__  `-`  ___/-. /
                 ___`. .'  /--.--\  `. . __
              ."" '<  `.___\_<|>_/___.'  >'"".
             | | :  `- \`.;`\ _ /`;.`/ - ` : | |
             \  \ `-.   \_ __\ /__ _/   .-` /  /
        ======`-.____`-.___\_____/___.-`____.-'======
                           `=---='
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                 佛祖保佑       永无BUG
        */
@RestController
@RequestMapping("/api/pay")
public class PayController extends BaseController {
    private final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(PayController.class);

    @Autowired
    private IUserExtService iUserExtService;

    @Autowired
    private IPayService iPayService;

    @Autowired
    private BuysService buysService;

    @Autowired
    private AlbumService albumService;


    /**
     * 解锁专辑
     *
     * @param userId
     * @param albId
     * @param payType
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/unlocked", method = RequestMethod.POST)
    public JSONObject unlocked(@RequestParam String userId, @RequestParam String albId, @RequestParam int payType) {
        if (payType == PayEnum.PAY_TYPE_RECHARGE.getId() || payType == PayEnum.PAY_TYPE_MEMBER.getId()) {
            return returnResult(PayEnum.PAY_PAYMENT_TYPE.getId(), "", PayEnum.PAY_PAYMENT_TYPE.getValue());
        }
        Album album = albumService.selectByPrimaryKey(albId);
        //验证用户积分
        UserExt userExt = iUserExtService.findUserExt(userId);
        if (userExt != null && album != null) {
            //积分大于等于现价
            BigDecimal presentPrice = BigDecimal.valueOf(Double.valueOf(album.getPresentPrice() == null ? "0" : album.getPresentPrice()));
            // TODO: 2017/10/24 0024  只有当消费的时候，才会根据不同的支付类型从用户帐户里获取不同的余额
            BigDecimal userOver = null;
            if (payType == PayEnum.PAY_TYPE_POINT.getId()) {
                userOver = new BigDecimal(userExt.getPoint());
            } else if (payType == PayEnum.PAY_TYPE_MONEY.getId()) {
                userOver = new BigDecimal(userExt.getMoney());
            }
            // TODO: 2017/10/24 0024   帐户余额与专辑现价进行比较，只有当余额大于等于现价，才能进行下一步操作
            if (userOver.compareTo(presentPrice) >= 0) {
                //创建订单记录
                Orders orders = iPayService.createOrder(payType, userId);
                //创建订单不为空才继续创建消费明细及解锁记录
                if (orders != null) {
                    //创建明细记录
                    int num = iPayService.createPayJournal(payType, orders.getOrderNo(), albId, presentPrice.toString());
                    if (num <= 0) {
                        return returnResult(PayEnum.PAY_FLOW_ERROR.getId(), "", PayEnum.PAY_FLOW_ERROR.getValue());
                    }

                    //创建解锁记录
                    Buys buys = buysService.saveBus(userId, orders.getOrderNo(), albId);
                    if (buys == null) {
                        return returnResult(PayEnum.PAY_BUYS_ERROR.getId(), "", PayEnum.PAY_BUYS_ERROR.getValue());
                    }
                } else {
                    return returnResult(PayEnum.PAY_ORDER_ERROR.getId(), "", PayEnum.PAY_ORDER_ERROR.getValue());
                }


                //更新用户信息
                BigDecimal point = null;
                if (presentPrice != null) {
                    userExt.setIcon(null);
                    // TODO: 2017/10/24 0024  根据不同的消费支付方式，修改用户不同的帐户余额
                    if (payType == PayEnum.PAY_TYPE_POINT.getId()) {
                        point = new BigDecimal(userExt.getPoint());
                        userExt.setPoint(point.subtract(presentPrice).longValue());
                    } else if (payType == PayEnum.PAY_TYPE_MONEY.getId()) {
                        point = new BigDecimal(userExt.getMoney());
                        userExt.setMoney(point.subtract(presentPrice).doubleValue());
                    }
                    UserExt userExt1 = iUserExtService.updateUserExt(userExt);
                    if (null == userExt1) {
                        return returnResult(PayEnum.PAY_USER_EXT_ERROR.getId(), "", PayEnum.PAY_USER_EXT_ERROR.getValue());
                    }
                } else {
                    return returnResult(PayEnum.PAY_ORDER_ERROR.getId(), "", PayEnum.PAY_ORDER_ERROR.getValue());
                }

            } else {
                return returnResult(PayEnum.PAY_POINT_LACK.getId(), "", PayEnum.PAY_POINT_LACK.getValue());
            }

        } else {
            return returnResult(PayEnum.PAY_ARGS_ERROR.getId(), "", PayEnum.PAY_ARGS_ERROR.getValue());
        }

        return returnResult(PayEnum.PAY_SUCCESS.getId(), "", PayEnum.PAY_SUCCESS.getValue());
    }


    /**
     * 创建订单
     *
     * @param userId
     * @param payType
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/payReady", method = RequestMethod.POST)
    public JSONObject payReady(@RequestParam String userId, @RequestParam int payType) {
        Orders orders = iPayService.createOrder(payType, userId);
        return returnResult(200, orders, "");
    }


    /**
     * 支付回调
     *
     * @param userId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/recharge", method = RequestMethod.POST)
    public JSONObject recharge(@RequestParam String userId, @RequestParam String rechargeId, @RequestParam int payType) {
        UserExt userExt = iUserExtService.findUserExt(userId);
        iPayService.payCallBack(rechargeId, payType, userExt);
        return returnResult(200, "", "");
    }


    /**
     * 获取专辑及用户的相关信息
     * isfirst：用户是否首充
     * isAtten：用户是否关注
     * isUnlock：用户是否解锁
     *
     * @param userId
     * @param albId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/albumUserInfo", method = RequestMethod.POST)
    public JSONObject albumUserInfo(@RequestParam String userId, @RequestParam String albId) {
        Map<String, Object> data = new HashedMap();
        List<Orders> orderses = iPayService.getOrderList(userId);
        Map<String, String> par = new HashedMap();
        par.put("userId", userId);
        par.put("albId", albId);
        Attention attention = iUserExtService.findUserAttention(par);

        Buys buys = new Buys();
        buys.setUserId(userId);
        buys.setAlbId(albId);
        List<Buys> buyses = buysService.getUserBuys(buys);

        data.put("isfirst", orderses.size() > 0 ? false : true);
        data.put("isAtten", attention == null ? false : true);
        data.put("isUnlock", buyses.size() > 0 ? true : false);

        return returnResult(200, data, "");
    }

    /**
     * 获取所有支付方式
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/rechargeList", method = RequestMethod.POST)
    public JSONObject recharge(@RequestParam String userId, @RequestParam String albId) {
        RedisUtils redisUtils = RedisUtils.getInstance();
        Map<String, Object> data = new HashedMap();
        if (redisUtils.exists(StaticResource.SYS_INIT_RECHARGE_KEY)) {
            //获取所有的支付类型
            Map<String, String> rechargeMap = redisUtils.hgetall(StaticResource.SYS_INIT_RECHARGE_KEY);
            List<JSONObject> rechargeList = new ArrayList();
            List<JSONObject> memberList = new ArrayList();

            Set<String> keys = rechargeMap.keySet();
            for (String key : keys) {
                JSONObject rechargeJson = JSONObject.parseObject(rechargeMap.get(key));
                int rechType = rechargeJson.getIntValue("rechType");
                if (rechType == PayEnum.PAY_TYPE_RECHARGE.getId()) {
                    rechargeList.add(rechargeJson);
                }
                if (rechType == PayEnum.PAY_TYPE_MEMBER.getId()) {
                    memberList.add(rechargeJson);
                }
            }

            data.put("recharge", rechargeList);
            data.put("member", memberList);
        }

        return returnResult(200, data, "");
    }
}
